<div id="kaoHeKaiLiaoYuan" style="height: 100%;width: 100%">
    <div  style="width:100%;text-align: right;background-color: #009E94;" >
        <input id="peiZhiCheJianKaiLiaoYuanAssessMonth" data-options="label:'考核月份',labelWidth:60,width:200" type= "text" class= "easyui-datebox" required ="required">
        <a id="kaiLiaoYuanSubmit" class="easyui-linkbutton" style="width: 80px;background-color:#a1af1a" plain=true><i class="fa fa-check-circle fa-lg fa-fw"></i>提交</a>
    </div>
    <div style="height:93%">
        <!--奖金表格-->
        <table id="peiZhiCheJianKaiLiaoYuan"></table>
    </div>
    <div id="peiZhiCheJianKaiLiaoYuanToolbar" style="display: none;">
        <div style="width: 150px;float: left">
            <a class="easyui-linkbutton" data-options="plain:true" onClick="addPeiZhiCheJianKaiLiaoYuanEmp()"><i class="fa fa-plus-square fa-fw" aria-hidden="true"></i>新增</a>
            <a class="easyui-linkbutton" data-options="plain:true">|</a>
            <a class="easyui-linkbutton" data-options="plain:true" onclick="javaScript:$('#peiZhiCheJianKaiLiaoYuan').edatagrid('destroyRow')"><i class="fa fa-trash fa-fw" aria-hidden="true"></i>删除</a>
        </div>
        <div style="width: 250px;float:right;text-align: right;padding-right: 10px">
            <a class="easyui-linkbutton" data-options="plain:true" onclick="javaScript:$('#peiZhiCheJianKaiLiaoYuan').edatagrid('saveRow')"><i class="fa fa-floppy-o fa-fw" aria-hidden="true"></i>保存</a>
        </div>
        <!--清除浮动-->
        <div style="clear: both"></div>
    </div>
    <form accept-charset=""></form>
    <script th:inline="none">
        //当前编辑行的索引
        var peiZhiCheJianKaiLiaoYuanIndex=0;

        //提交数据
        $("#kaiLiaoYuanSubmit").click(function () {
            $.messager.confirm('确认对话框', '<span style="color: red">注意：提交会初始化当月(技术组长、主管)的绩效考核数据,</span>您确定要提交吗？', function(r){
                if (r){
                    //获取考核数据：判断最终综合绩效是否有值
                    var rows = $("#peiZhiCheJianKaiLiaoYuan").datagrid("getRows");
                    // console.log(rows)
                    // 1、封装年月和部门---全局变量设定在jxAssessGlobalVariable的js文件中；
                    rows.forEach(function (val) {
                        val.assessYear=pzcj_currentYear;
                        val.assessMonth=pzcj_currentMonth;
                        val.assessDept=pzcj_currentDept;
                    })
                    //获取页脚行的数据：合计：班级的
                    rows=JSON.stringify({maps:window.kailiaoyuanFooters,jxAssessPzcjs:rows})
                    // rows=JSON.stringify(rows)
                    //提交数据
                    var resultMessage = commonAjax("post","/jx/pzcj/addKaiLiaoYuanAssessData",rows,"application/json;charset=utf-8");
                    if (resultMessage.status==200){
                        //清空数据----footer：行尾
                        $("#peiZhiCheJianKaiLiaoYuan").datagrid("loadData", {total: 0, rows: [],footer:[]});
                        windowsOperation(null,null,resultMessage)
                    }else {
                        layer.msg(resultMessage.msg,{"icon":5})
                    }
                }
            });
        })

        //绩效考核表添加事件
        function addPeiZhiCheJianKaiLiaoYuanEmp(){
            //添加html内容
            let html="<div id='addPeiZhiCheJianKaiLiaoYuanEmpDialog'></div>"
            //往表格旁边添加div
            $("#peiZhiCheJianKaiLiaoYuan").after(html);
            $("#addPeiZhiCheJianKaiLiaoYuanEmpDialog").dialog({
                title:'添加考核人员',
                width:300,
                height:500,
                onClose:function () {
                    //console.log("触发了  $(\"#addPeiZhiCheJianKaiLiaoYuanEmpDialog\")的onClose事件")
                    $("#addPeiZhiCheJianKaiLiaoYuanEmpDialog").remove();
                },
                onOpen:function () {
                    console.log("addPeiZhiCheJianKaiLiaoYuanEmpDialog_onOpen")
                    //把id为addPeiZhiCheJianKaiLiaoYuanEmpDialogContent添加到窗口栏中
                    $("#addPeiZhiCheJianKaiLiaoYuanEmpDialog").append(addPeiZhiCheJianKaiLiaoYuanEmpHtmlContent())
                    //解析eayui组件：动态的加载进来的easyui组件，需要进行解析
                    $.parser.parse("#addPeiZhiCheJianKaiLiaoYuanEmpDialogContent");
                    //禁用岗位
                    $("#addPeiZhiCheJianKaiLiaoYuanEmpDialogContentPost").combobox('readonly',true);
                    $("#addPeiZhiCheJianKaiLiaoYuanEmpDialogContentDept").combotree({ //部门
                        //panelHeight:"150",
                        onChange:function (newValue,oldValue) { //部门内容改变事件
                            $("#addPeiZhiCheJianKaiLiaoYuanEmpDialogContentPost").combobox({
                                valueField:'code',
                                textField:'name',
                                prompt:'请选择部门',
                                panelHeight:"auto",
                                url:"/jxIndex/getPostByDept?pkDept="+newValue,
                                onClick:function (row) {  //岗位内容改变事件
                                    console.log("岗位内容改变事件",row)
                                    $("#addPeiZhiCheJianKaiLiaoYuanEmpDialogContentEmp").datagrid({
                                        url:"/jxEmp/getEmpByPkDeptAndPostId",
                                        queryParams:{
                                            postId:row.id,
                                            pkDept:row.pkDept
                                        },
                                        onDblClickRow:function (index, row) {  //双击
                                            console.log("员工双击",row)
                                            //添加综合绩效奖
                                            $("#peiZhiCheJianKaiLiaoYuan").edatagrid('addRow',{
                                                row:{
                                                    empCode:row.empCode,
                                                    empName:row.empName,
                                                    empGroup:row.empGroup,
                                                    postName:row.postName
                                                }
                                            })
                                            totalPeiZhiCheJianKaiLiaoYuan()
                                        }
                                    })
                                }
                            })
                            //启用岗位
                            $("#addPeiZhiCheJianKaiLiaoYuanEmpDialogContentPost").combobox('readonly',false);

                        }
                    })
                }
            })
        }

        //dialog内容
        function addPeiZhiCheJianKaiLiaoYuanEmpHtmlContent(){
            var content="<div id=\"addPeiZhiCheJianKaiLiaoYuanEmpDialogContent\">\n" +
                "                <input id=\"addPeiZhiCheJianKaiLiaoYuanEmpDialogContentDept\" class=\"easyui-combotree\" data-options=\"label:'部门',labelWidth:'40',url:'/jxIndex/getDeptByPkOrg?pkOrg=0001O110000000001HET'\" style=\"width: 100%\">\n" +
                "                <input id=\"addPeiZhiCheJianKaiLiaoYuanEmpDialogContentPost\" class=\"easyui-combobox\" data-options=\"label:'岗位',labelWidth:'40'\" style=\"width: 100%\">\n" +
                "                <table id=\"addPeiZhiCheJianKaiLiaoYuanEmpDialogContentEmp\" class=\"easyui-datagrid\" data-options=\"striped:'true', nowrap:false, fitColumns: true,scrollbarSize:0\">\n" +
                "            <thead>\n" +
            "            <tr>\n" +
        //    "            <th data-options=\"field:'id',checkbox:true,align:'center'\">id</th> \n" +
            "            <th data-options=\"field:'empName',width: '50%',align:'center'\">姓名</th>\n" +
            "            <th data-options=\"field:'empCode',width: '50%',align:'center'\">工号</th> \n" +
            "            </tr>\n" +
            "            </thead>\n" +
                "</table>\n" +
                "                </div>";
            return content;
        }

        var date= new Date();
        //选择月份加载月份数据
        $("#peiZhiCheJianKaiLiaoYuanAssessMonth").datebox({
            onSelect: function(date){
                $("#peiZhiCheJianKaiLiaoYuan").datagrid("loadData",[])
                var currentYear=date.getFullYear()
                var currentMonth=date.getMonth()+1
                kaiLiaoYuanInit(currentYear,currentMonth)
                addPZCJData("peiZhiCheJianKaiLiaoYuan",window.JX_PZCJ_KAILIAOYUAN,"1002O110000000000MMB",currentYear,currentMonth)
            }

        })

        //进页面默认调用当月数据
        kaiLiaoYuanInit(date.getFullYear(),date.getMonth()+1)

//绩效考核表初始化方法
        function kaiLiaoYuanInit(currentYear,currentMonth) {
            window.pzcj_currentYear = currentYear;//年
            window.pzcj_currentMonth = currentMonth; //月
            var currentYM=currentYear+"年"+currentMonth+"月";
            var kaiLiaoYuan = {
                init: [//表头
                    [
                        {"title": ' <span style="font-size: 18px">开料员综合绩效奖</span><span style="color: #009E94">(绩效奖金标准*0.8+第一次打板金额(B1）)*出勤率-绩效扣款(C1)</span>',"align": "center", "colspan":12},

                    ],
                    [  {"title": '考核部门（科室）:',"align": "center", "colspan":3},
                        {"field": 'id3', "title": "生产部/配制车间","align": "center", "colspan":2},
                        {"title": '', "align": "center","colspan":3},
                        {"title": '考核周期:',"align": "center"},
                        {"field": 'id2', "title": currentYM, "align": "center","colspan":2},
                        {"field": 'resultMoney', "title": '最终综合<br/>绩效（元）', "width": 30,"rowspan":2,"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
                    ],
                    [
                        {"field": 'id', "title": 'ID', "width": 0, "align": "center", "hidden": "true"},
                        {"field": 'empName', "title": '姓名', "width": 30, "align": "center"},
                        {"field": 'empCode', "title": '工号', "width": 30, "align": "center"},
                        {
                        "field": 'postName',
                        "title": '岗位',
                        "width": 30,
                        "align": "center"
                        },
                        {"field": 'empGroup', "title": '班组', "width": 30, "align": "center"},
                        {
                        "field": 'productivity',
                        "title": '个人生产<br/>效率(%)',
                        "width": 30,
                        "align": "center",
                        "editor": {"type": "textbox", "options": {"precision":2,"onChange":peiZhiCheJianKaiLiaoYuanProductivity}}},
                        {"field": 'performanceBonus', "title": '绩效奖金<br/>标准', "width": 30,"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
                         {"field": 'dabanSuccess', "title": '一次打板<br/>成功率(%)', "width": 30,"align": "center","editor": {"type": "textbox", "options": {"onChange":peiZhiCheJianKaiLiaoYuanDabanSuccess}}},
                         {"field": 'dabanMoney', "title": '第一次打板<br/>金额', "width": 30,"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
                         {"field": 'deduct', "title": '绩效扣款', "width": 30,"align": "center","editor": {"type": "textbox", "options": {"onChange":peiZhiCheJianKaiLiaoYuanAttendanceRateAndDeduct}}},
                         {"field": 'attendanceRate', "title": '出勤率(%)', "width": 30,"align": "center","editor": {"type":"textbox", "options": {"onChange":peiZhiCheJianKaiLiaoYuanAttendanceRateAndDeduct}}},
                           //{"field": 'isAffirm', "title": '员工确认', "width": 20,"align": "center"}
                    ]]

            }

            //奖金基数表格
            $("#peiZhiCheJianKaiLiaoYuan").edatagrid({
                nowrap: false,
                columns: kaiLiaoYuan.init,
                showFooter: true,
                autoSave:true,
                fitColumns: true,
                //scrollbarSize:0,  //最右侧多出来的去除
                toolbar:"#peiZhiCheJianKaiLiaoYuanToolbar",
                onBeforeEdit:function (index, row) { //编辑器打开触发事件
                    peiZhiCheJianKaiLiaoYuanIndex=index;//保存当前索引

                },
                onAfterEdit:function (index, row) {
                   // console.log("在用户完成编辑一行的时候触发:统计最终综合绩效")
                    totalPeiZhiCheJianKaiLiaoYuan();
                },
                onDestroy:function (index,row) { //删除一行触发事件
                    totalPeiZhiCheJianKaiLiaoYuan();
                }

            })
        }

        //合计最终综合绩效
        function totalPeiZhiCheJianKaiLiaoYuan() {

            var rows = $("#peiZhiCheJianKaiLiaoYuan").datagrid("getRows");
            //合计最终综合绩效
            var  result=0;
            //封装统计每个班组的班组名、班组人的个数、班组的总绩效奖金
            var arrays=[];          //[{"name": "A","total": 5,"totalValue": 150.36}, {"name": "B","total": 3,"totalValue": 150}]
            rows.forEach(function (row) {
                var val=Number(row.resultMoney)
                if (val){
                    result+=val
                }
                //统计有多少种类型
               totalJxType(arrays,row);

            })
            //console.log("统计有多少种类型",arrays)
            window.kailiaoyuanFooters=[{empCode: "合计", resultMoney: fomatFloat(result,2)}]

            arrays.forEach(function (value) {
                var ar={};
                ar.empCode=value.name+"组平均绩效奖金";
                ar.total=value.total;
                ar.groupTotalBonus=fomatFloat(value.totalValue,2);
                ar.resultMoney=fomatFloat(Number(value.totalValue)/Number(value.total),2)
                window.kailiaoyuanFooters.push(ar)  //封装行尾中
            })

            //添加页脚行方法
            $("#peiZhiCheJianKaiLiaoYuan").edatagrid('reloadFooter', window.kailiaoyuanFooters)

        }

        //统计封装班组、班组总奖金、班组人数
        function totalJxType(b,row) {
            var empGroup=row.empGroup;      //班组
            var result={};             // {"name": "A","totalNum": 5,"totalValue": 150.36},
            let temp=1;
            // [{"name": "A","total": 5,"avg": 150.36}, {"name": "B","total": 3,"totalValue": 150.36}]
            if (b.length>0){
                b.forEach(function (val) {
                    //判断empGroup在不在这个数组中，若在临时值改为0
                    if (empGroup && empGroup != "" && val.name == empGroup){
                        temp=0;
                        //第二次以上：处理对象result
                        val.total+=1;
                        val.totalValue= Number(val.totalValue)+Number(row.resultMoney);
                    }
                })
            }

            //第一次添加到数组中
            if (temp){
                result.name=empGroup;     // 班组
                result.total=1;     //个数
                result.totalValue=row.resultMoney;  //个人最终绩效奖金
                b.push(result);
            }
        }

        //个人生产效率触发事件:计算绩效奖金标准
        function peiZhiCheJianKaiLiaoYuanProductivity(newValue,oldValue) {
            if(newValue){
                newValue = Number(newValue)
                var ed = $('#peiZhiCheJianKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianKaiLiaoYuanIndex,
                    field: 'performanceBonus'
                }); //绩效奖金标准编辑器对象
                var performanceBonusJ = ed.target;  // 绩效奖金标准jquery对象
                var performanceBonus;
                //1、x ≤ 97% 或 x ≥ 105%=0；2、97% < x ≤ 99%或者103% ≤ x  < 105%=400；
                // 3、100% < x < 103%或者99% < x < 100%=500；4、x=100%=600
                if (newValue <= 95 || newValue >= 105) {
                    performanceBonus=0;
                } else if ((95 < newValue && newValue <= 99) || (103 <= newValue && newValue < 105)) {
                    performanceBonus=400
                } else if ((100 < newValue && newValue < 103) || (99 < newValue && newValue < 100)) {
                    performanceBonus=500
                } else if (newValue ==100) {
                    performanceBonus=600
                } else {
                    var productivity= getEditObject("productivity") //个人生产
                    productivity.textbox("setValue", "")
                    layer.msg("请输入正确的值！")
                    return
                }
                performanceBonusJ.textbox("setValue",performanceBonus)

                //为0的时候触发一下打板成功率，为0，防止用户在填完整行后，又去修改
                //获取值打板成功率值，
                var dabanSuccess = $('#peiZhiCheJianKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianKaiLiaoYuanIndex,
                    field: 'dabanSuccess'
                }).target.textbox("getValue");
                //调用一次打板成功率触发事件方法
                peiZhiCheJianKaiLiaoYuanDabanSuccess(dabanSuccess)
                peiZhiCheJianKaiLiaoYuanresultMoney() //计算最终绩效的方法
            }

        }

        //一次打板成功率触发事件:计算 第一次打板金额(B1）
        function peiZhiCheJianKaiLiaoYuanDabanSuccess(newValue,oldValue) {
            if (newValue) {
                newValue = Number(newValue)
                var ed = $('#peiZhiCheJianKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianKaiLiaoYuanIndex,
                    field: 'dabanMoney'
                }); //第一次打板金额(B1）编辑器对象
                var dabanMoneyJ = ed.target;  // 绩效奖金标准jquery对象
                //B1奖金获取方式：有两步
                //第一步 先获取一次打板通过率 (Y) 的:获取方式3种条件
                var y;   //一次打板通过率
                if (newValue >= 75) { // 1、Y >=75%按100%；
                    y = 1
                } else if (50 <= newValue && newValue < 75) {//2、50%≤ Y < 75%，占比例计算：如56%，则56%除以75%的公式；
                    y = newValue / 75;
                } else if (newValue < 50 ) {//3、Y >50%,Y=0%
                    y = 0
                } else {
                    var dabanSuccess= getEditObject("dabanSuccess")
                    dabanSuccess.textbox("setValue", "")
                    layer.msg("请输入正确的值")
                    return
                }
                //第二步然后通过公式：A1*一次打板通过率(Y)*0.2计算出最终的B1奖金
                var performanceBonusJ = $('#peiZhiCheJianKaiLiaoYuan').datagrid('getEditor', {
                    index: peiZhiCheJianKaiLiaoYuanIndex,
                    field: 'performanceBonus'
                }).target; //绩效奖金标准编辑器对象
                var performanceBonus = performanceBonusJ.textbox("getValue");
                if (performanceBonus) {
                    var dabanMoney=fomatFloat(Number(performanceBonus) * y * 0.2, 2)
                    dabanMoneyJ.textbox("setValue",dabanMoney)
                } else {
                    //清空一次打板成功率用户输入的值
                    var dabanSuccess= getEditObject("dabanSuccess")
                    dabanSuccess.textbox("setValue", "")
                    layer.msg("请先计算出绩效奖金标准的值")
                }

                peiZhiCheJianKaiLiaoYuanresultMoney() //计算最终绩效的方法
            }

        }

        //扣款绩效和出勤率触发事件
        function peiZhiCheJianKaiLiaoYuanAttendanceRateAndDeduct() {
            //console.log("扣款绩效")
            peiZhiCheJianKaiLiaoYuanresultMoney() //计算最终绩效的方法
        }

        //计算最终绩效的方法:(计算绩效奖金标准*0.8+第一次打板金额(B1）)*出勤率-绩效扣款(C1)
        function peiZhiCheJianKaiLiaoYuanresultMoney() {
            //为了以后有可能会更改字段的位置或添加问题，不使用获取编辑器对象数组的方法
           console.log("计算最终绩效的方法")
            //绩效奖金标准
            var performanceBonus = getEditObject("performanceBonus").textbox("getValue");
            performanceBonus=performanceBonus?Number(performanceBonus):0;
            //第一次打板金额
            var dabanMoney = getEditObject("dabanMoney").textbox("getValue");
            dabanMoney=dabanMoney?Number(dabanMoney):0;
            //出勤率
            var attendanceRate = getEditObject("attendanceRate").textbox("getValue");
            attendanceRate=attendanceRate?Number(attendanceRate):100;

            //绩效扣款
            var deduct = getEditObject("deduct").textbox("getValue");
            deduct=deduct?Number(deduct):0;
            // 获取最终绩效奖金编辑器对象
            var resultMoney = getEditObject("resultMoney");
            resultMoney.textbox("setValue",fomatFloat((performanceBonus*0.8+dabanMoney)*attendanceRate/100,2)-deduct);

        }

        //获取当前编辑行指定的jquery对象
        function getEditObject(fieldValue) {
            var j = $('#peiZhiCheJianKaiLiaoYuan').datagrid('getEditor', {
                index: peiZhiCheJianKaiLiaoYuanIndex,
                field: fieldValue
            }).target; //第一次打板成功率编辑器对象
            return j
        }
    </script>
</div>